package com.icart.controller.personController;

import com.icart.context.HttpUserContext;
import com.icart.context.storage.ContextStorage;
import com.icart.context.storage.SessionContextStorageImpl;
import com.icart.repositories.CustinfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/person")
public class MytcController {

    @Autowired
    HttpServletRequest request;
    @Autowired
    CustinfoRepository custinfoRepository;

    @RequestMapping("/mytc")
    public String mytc(Model model) {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");
        Date dates=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time=format.format(dates);//获取当前系统时间
        List list=custinfoRepository.createNativeQuery("select cc.tcoid,cc.tcname,(select n.chnname from bi_chn n where n.chnid=cc.creatchn)chnname,DATE_FORMAT(cc.useenddate,'%Y-%m-%d')useenddate" +
                " from cu_custtc cc where useenddate>='"+time+"' and cc.custid="+userContext.getCustid()+" order by useenddate");
        model.addAttribute("list",list);
        List list1=custinfoRepository.createNativeQuery("select cc.tcoid,cc.tcname,(select n.chnname from bi_chn n where n.chnid=cc.creatchn)chnname,DATE_FORMAT(cc.useenddate,'%Y-%m-%d')useenddate" +
                " from cu_custtc cc where useenddate<'"+time+"' and cc.custid="+userContext.getCustid()+" order by useenddate desc");
        model.addAttribute("list1",list1);
        return "person/tc/tchome";
    }

    @RequestMapping("/tcdetail")
    public String tcdetail(Model model) {
        String tcoid=request.getParameter("tcoid");
        List list=custinfoRepository.createNativeQuery("select cc.tcoid,cc.tcname,(select n.chnname from bi_chn n where n.chnid=cc.creatchn)chnname,DATE_FORMAT(cc.useenddate,'%Y-%m-%d')useenddate,cc.remark" +
                " from cu_custtc cc where cc.tcoid="+tcoid);
        model.addAttribute("list",list.get(0));
        /*服务项目*/
        List servitem=custinfoRepository.createNativeQuery("select (select n.servitemname from bi_servitem n where n.servitemid=m.servitem)servitemname,m.tcount from cu_custtcservitem m " +
                " where m.tcoid="+tcoid);
        model.addAttribute("servitem",servitem);
         /*材料*/
        List met=custinfoRepository.createNativeQuery("select (select mname from bi_metinfo where cid=m.metaitemid)mname,m.mcount from cu_custtcmeteitem m " +
                " where m.tcoid="+tcoid);
        model.addAttribute("met",met);

        return "person/tc/tcdetail";
    }

}